package com.kg.tombs;

import com.kg.tombs.controller.AiController;
import com.kg.tombs.controller.DataController;
import com.kg.tombs.controller.ExcelController;
import com.kg.tombs.controller.Neo4jController;
import com.kg.tombs.db.MongoVerticle;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.CorsHandler;
import io.vertx.ext.web.handler.StaticHandler;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class TombsVerticle extends AbstractVerticle {

    private static final Integer PORT = 6688;

    @Override
    public void start(Promise<Void> startPromise) throws Exception {
        MongoVerticle dbVerticle = new MongoVerticle();
        vertx.deployVerticle(dbVerticle)
                .compose(res -> {

                    ExcelController excelController = new ExcelController(vertx, dbVerticle);
                    DataController dataController = new DataController(vertx, dbVerticle);
                    Neo4jController neo4jController = new Neo4jController(vertx, dbVerticle);
                    AiController aiController = new AiController(vertx,dbVerticle);

                    Router router = Router.router(vertx);
                    // 添加CORS处理程序
                    router.route().handler(CorsHandler.create("*"));
                    router.route().handler(BodyHandler.create());

                    router.route().handler(BodyHandler.create()).handler(routingContext -> {
                        log.info("[{}] >>> {} {}",
                                LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")),
                                routingContext.request().method(),
                                routingContext.request().uri());
                        routingContext.next();
                    });

                    // 上传文件路由
                    router.post("/api/upload").handler(BodyHandler.create().setUploadsDirectory("uploads"));
                    router.post("/api/upload").handler(excelController::upload);

                    // POST路由
                    router.post("/api/ask").handler(aiController::ask);

                    // GET路由
                    router.get("/api/getAll").handler(dataController::getAll);
                    router.get("/api/getFullGraph").handler(neo4jController::getFullGraph);
                    router.get("/api/getCollections").handler(dataController::getCollections);

                    // 静态文件服务 - Vue打包文件
                    StaticHandler staticHandler = StaticHandler.create("webroot")
                            .setCachingEnabled(true)
                            .setMaxAgeSeconds(86400)
                            .setIndexPage("index.html");
                    router.route("/*").handler(staticHandler);

                    router.route().failureHandler(routingContext -> {
                        Throwable failure = routingContext.failure();
                        if (failure != null) {
                            log.error("路由处理异常:", failure);
                            routingContext.response().setStatusCode(500).end("Internal Server Error");
                        }
                    });

                    return vertx.createHttpServer()
                            .requestHandler(router)
                            .listen(PORT);
                }).onSuccess(server -> {
                    log.info("HTTP server started on port {}",PORT);
                    startPromise.complete();
                })
                .onFailure(startPromise::fail);
    }
}
